<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        .box{width: 400px;height: 300px;margin: 20px auto;border: solid 1px black;}
        .box ul{margin: 0;padding: 0;list-style: none;display: flex;background: #ccc;border-bottom: solid 1px black;height: 40px;}
        .box ul li{flex: 1;border-right: solid 1px #fff;border-left: solid 1px #fff;text-align: center;line-height: 40px;cursor: pointer;}
        .box ul li.active{background: red; color: #fff;}

        .box .items{height: 259px;}
        .items div{width: 400px;height: 259px;display: none;}
        .items div:nth-child(1){background: #3aa}
        .items div:nth-child(2){background: #3a3}
        .items div:nth-child(3){background: #aa3}
        .items div:nth-child(4){background: #a3a}
        .items div:nth-child(5){background: #33a}
        .items div.active{display: block}
    </style>
</head>
<body>
    <div class="box">
        <ul>
            <li class="active">手机</li>
            <li>电脑</li>
            <li>平板</li>
            <li>耳机</li>
            <li>零食</li>
        </ul>
        <div class="items">
            <div class="active">好多手机</div>
            <div>好多电脑</div>
            <div>好多平板</div>
            <div>好多耳机</div>
            <div>好多吃的</div>
        </div>
    </div>
</body>
<script>
    // 选项卡：点击不同的按钮，切换对应的内容

    // 1. 选择元素
    var ali = document.querySelectorAll(".box ul li");
    var adiv = document.querySelectorAll(".items>div");

    // 默认选中的索引
    var index = 0;

    // 2. 绑定点击事件
    // console.log(ali)
    for(var i=0;i<ali.length;i++){

        // 5. 提前给每个li都绑定一个自定义的索引
        // ali[i].setAttribute("xuhao", i);
        ali[i].xuhao = i;

        ali[i].onclick = function(){
            // 3. 设置点击元素的样式之前，先清除默认索引对应元素的样式
            ali[index].className = "";
            adiv[index].className = "";

            // console.log(i);     // 循环结束后的计数器
            // console.log(ali[i]);     // undefined
            // console.log(this);   // 点击的li元素
            // 4. 给当前点击的元素设置样式
            this.className = "active";
            // adiv[this.getAttribute("xuhao")].className = "active";
            adiv[this.xuhao].className = "active";

            // 6. 点击之后，修改默认索引，为本次点击的li的索引
            // index = 本次点击的li的索引
            // index = this的索引
            // index = this.getAttribute("xuhao");
            index = this.xuhao;
        }
    }



    // 异步
    // 闭包
    

</script>
</html>